package com.wjc.common

import android.content.res.Resources
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.util.*

/**
 * ClassName: com.wjc.common
 * Description:共同的一些扩展函数
 * JcChen on 2021.05.29.17:06
 */

fun ViewModel.launch(
    block: suspend CoroutineScope.() -> Unit,
    onError: (e: Throwable) -> Unit = {},
    onComplete: () -> Unit = {}
) {
    viewModelScope.launch(CoroutineExceptionHandler { _, e -> onError(e) }) {
        try {
            block.invoke(this)
        } finally {
            onComplete()  // 保证 onComplete 一定执行
        }
    }
}

/**
 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
 *     5.0f.dpToPx
 */
val Float.dp
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        this,
        Resources.getSystem().displayMetrics
    )


/**
 * 获取指定范围内的随机数[]
 */
fun getRandom(start: Int, end: Int): Int {
    return ((start + Math.random() * (end - start + 1)).toInt())
}

/**
 *  通过名字，查找并加载 mipmap 下的图片,必须同时传入两个参数
 * @param null
 * @return
 */
fun setImageResourceWithType(view: ImageView, srcName: String?, type: Int? = 0) {
    if (type != null) {
        if (type <= 0) {
            view.visibility = View.GONE
            return
        }
    }

    val drawableId = view.resources.getIdentifier(srcName, "mipmap", view.context.packageName)
    if (drawableId <= 0) {
        view.visibility = View.GONE
        return
    }
    view.setImageResource(drawableId)
    view.visibility = View.VISIBLE
}
